package com.yanwq.sayhi.controller.club.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.yanwq.sayhi.R;
import com.yanwq.sayhi.base.BaseToolbarActivity;
import com.yanwq.sayhi.common.client.OkJsonObjectResponseCallback;
import com.yanwq.sayhi.common.client.OkRequestParams;
import com.yanwq.sayhi.common.client.OkRestClient;
import com.yanwq.sayhi.common.constant.CacheConstant;
import com.yanwq.sayhi.common.event.ClubEvent;
import com.yanwq.sayhi.common.tool.CropTool;
import com.yanwq.sayhi.controller.user.UserMgr;
import com.yanwq.sayhi.dao.bean.Club;
import com.yanwq.sayhi.dao.bean.ClubVip;
import com.yanwq.sayhi.dao.bean.User;
import com.yanwq.sayhi.widget.MToast;
import com.yanwq.sayhi.widget.SelectDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class ClubAddActivity extends BaseToolbarActivity {
    @BindView(R.id.club_avatar)
    ImageView mIVAvatar;
    @BindView(R.id.club_name)
    EditText mETName;
    @BindView(R.id.club_motto)
    EditText mETMotto;
    @BindView(R.id.club_pwd)
    EditText mETPwd;
    @BindView(R.id.club_permission)
    TextView mTVPermission;

    @OnClick(R.id.club_avatar)
    void cropAvatar() {
        mCropTool.pick(this);
    }

    private String mFileName;
    private File mPhotoFile;
    private boolean hasAvatar;
    private JSONObject mAvatar;
    private CropTool mCropTool;

    private int mPermission;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_club_add);
    }

    @Override
    public void init() {
        mFileName = CacheConstant.getRandomFileName();
        mPhotoFile = new File(CacheConstant.getPhotoPath(), mFileName);
        hasAvatar = false;
        mAvatar = null;
        mCropTool = new CropTool();
    }

    @Override
    public void initView() {
        mToolbar.setTitle("创建俱乐部");

        mTVPermission.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<SelectDialog.Item<Integer>> list = new ArrayList<SelectDialog.Item<Integer>>();
                list.add(new SelectDialog.Item<Integer>("公开", 0));
                list.add(new SelectDialog.Item<Integer>("需要密码", 1));
                list.add(new SelectDialog.Item<Integer>("需要申请", 2));
                SelectDialog<Integer> selectDialog = new SelectDialog<>(ClubAddActivity.this, list);
                selectDialog.setOnSelectedListener(new SelectDialog.OnSelectedListener<Integer>() {
                    @Override
                    public void onSelected(String item, Integer integer) {
                        mPermission = integer;
                        mTVPermission.setText(item);

                        if (integer == 1) {
                            mETPwd.setVisibility(View.VISIBLE);
                        } else {
                            mETPwd.setVisibility(View.GONE);
                        }
                    }
                });
                selectDialog.show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_send, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        send();
        return true;
    }

    private void send() {
        if (!hasAvatar) {
            MToast.showShort(ClubAddActivity.this, "请填俱乐部头像");
            return;
        }

        if (mETName.getText().length() == 0) {
            MToast.showShort(ClubAddActivity.this, "请填俱乐部名称");
            return;
        }

        if (mETMotto.getText().length() == 0) {
            MToast.showShort(ClubAddActivity.this, "请填俱乐部签名");
            return;
        }

        if (mPermission == 1 && mETPwd.length() == 0) {
            MToast.showShort(ClubAddActivity.this, "请填俱乐部密码");
            return;
        }
        if (mAvatar == null) {
            uploadAvatar();
        } else {
            add();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mCropTool.crop(mPhotoFile, this, requestCode, resultCode, data, new CropTool.CropCallback() {
            @Override
            public void onComplete(Uri resultUri) {
                mIVAvatar.setImageURI(resultUri);
                hasAvatar = true;
            }
        });
    }

    private void uploadAvatar() {
        OkRequestParams params = new OkRequestParams();
        params.put("mf", mFileName, mPhotoFile);

        OkRestClient.getInstance().post(this, "/oss/picture", params, new OkJsonObjectResponseCallback() {
            @Override
            public void onStart() {
                showProgressDialog("正在上传头像");
            }

            @Override
            public void onSuccess(JSONObject jsonObject) {
                mAvatar = jsonObject;
                add();
            }

            @Override
            public void onFail(int status, String s, Throwable throwable) {
                super.onFail(status, s, throwable);
                cancelProgressDialog();
            }

            @Override
            public void onStop() {
            }
        });
    }

    private void add() {
        Club club = new Club();
        club.setPhotoThumbUrl(mAvatar.getString("picThumbUrl"));
        club.setPhotoMediumUrl(mAvatar.getString("picMediumUrl"));
        club.setPhotoOriginUrl(mAvatar.getString("picOriginUrl"));
        club.setName(mETName.getText().toString());
        club.setMotto(mETMotto.getText().toString());
        club.setPassword(mETPwd.getText().toString());
        club.setPermission(mPermission);
        User user = UserMgr.get();
        ClubVip clubVip = new ClubVip();
        clubVip.setName(user.getNickname());
        clubVip.setUser(user);
        clubVip.setClub(club);

        OkRestClient.getInstance().post(this, "/clubVip/create", clubVip, new OkJsonObjectResponseCallback() {
            @Override
            public void onStart() {
                showProgressDialog("正在创建");
            }

            @Override
            public void onSuccess(JSONObject jsonObject) {
                MToast.showShort("恭喜，俱乐部已成立！！");
                setResult(0xf1);
                delayFinish();
                EventBus.getDefault().post(new ClubEvent(ClubEvent.CREATED));
            }

            @Override
            public void onStop() {
                cancelProgressDialog();
            }
        });
    }
}
